package com.rodirod.vrmonitor;

import com.rodirod.vrmonitor.R;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;

public class RaceSettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener,Constants {

	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        // get the name of the race
		String race_name = this.getIntent().getStringExtra(M_EXTRA_REGATE_NAME);

        getPreferenceManager().setSharedPreferencesName(race_name);
        getSharedPreferences(race_name,Context.MODE_PRIVATE).registerOnSharedPreferenceChangeListener(this);

        addPreferencesFromResource(R.xml.race_settings);
    }
	
	public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
		String summary = null;
    	Object value = sp.getAll().get(key);
    	if (value != null && value instanceof String)
    		value = notEmpty(sp.getString(key, null));
    	
    	summary = (value==null)?"":"Actual value : " + (String)value;
    	
    	if (summary!=null)
    	{
    		PreferenceScreen ps = getPreferenceScreen();
    		if (ps!=null)
    		{
    			Preference p = ps.findPreference(key);
    			if (p!=null)
    			{
    				p.setSummary(summary);
    			} 
    		}
    	}
    }
	
	private String notEmpty(String s)
    {
    	if (s!=null && s.trim().length()==0)
    	{
    		return null;
        }
        return s;
    }

	@Override
	protected void onPause() {
		super.onPause();
		// define the result
		String race_name = this.getIntent().getStringExtra(M_EXTRA_REGATE_NAME);
		SharedPreferences sp = getSharedPreferences(race_name,Context.MODE_PRIVATE);
		String url = sp.getString("base_url", null);
		if (null==url) {
			setResult(RESULT_CANCELED);
		} else {
			setResult(RESULT_OK);
		}

	}
	
	

}
